package com.jeady.jTools.feedback

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.jeady.jTools.R
import org.json.JSONArray
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

class FeedbackActivity() : AppCompatActivity() {
    val TAG = "MainActivity"
    lateinit var msg_list_container: LinearLayout
    lateinit var handler: Handler
    var isTouching = false
    var msgCount = 0
    var msgLast: JSONObject = JSONObject()
    var stopEmergency = 0

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        msg_list_container = findViewById(R.id.vll_msg_container)
        val etMsg = findViewById<EditText>(R.id.et_msg)
        val _focus: ScrollView = findViewById(R.id.sv_msg_list)
        val btnSendMsg = findViewById<TextView>(R.id.btn_send_msg)
        val tvState = findViewById<TextView>(R.id.tv_state)

        handler = Handler(Looper.myLooper()!!){
            when(it.what){
                0 -> {
                    if(it.arg1 == 200){
                        val response = it.obj.toString()
//                        Log.e(TAG, "onCreate: $response")
                        if(response.startsWith("operate") && (!response.endsWith("]"))) {
                                    Toast.makeText(this, "发送成功，等待消息同步", Toast.LENGTH_SHORT).show()
                                    return@Handler true
                        }
                        if(response == "[]"){
//                            Toast.makeText(this, "同步完成，无新消息", Toast.LENGTH_SHORT).show()
                            tvState.setTextColor(getColor(R.color.black))
                            return@Handler true
                        }
                        tvState.setTextColor(getColor(R.color.green))

                        val arr = JSONArray(it.obj.toString())
                        for(index in 0 until arr.length()){
                            Log.e(TAG, "onCreate: " +  arr.get(index))
                            msgLast = arr.getJSONObject(index)

                            if(msgLast["date"].toString().indexOf("!") != -1){  // 有新版本
                                val cm: ClipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
                                val da = ClipData.newPlainText("new_addr", msgLast["msg"].toString())
                                cm.setPrimaryClip(da)
                                Toast.makeText(this, "新版本下载地址已复制，粘贴到浏览器下载", Toast.LENGTH_LONG).show()
                                if(msgLast["date"].toString().indexOf("!!") != -1){ // 强制更新
                                    stopEmergency = -1
                                    val msg = Message()
                                    msg.what = 1
                                    msg.obj = "请下载新版本"
                                    handler.sendMessage(msg)
                                    return@Handler true
                                }
                                continue
                            }
//                                obj.put("date", obj["date"].toString().
//                                replaceFirst("99",
//                                    String.format("%2s",
//                                        SimpleDateFormat("MM", Locale.CHINA).format(Date()))))
                            msgCount++
                            addMsg(this, msgLast["msg"].toString(), msgLast["date"].toString())
                        }
                        Log.e(TAG, "onCreate: 当前消息数量： $msgCount")

//                        Toast.makeText(this, String.format("%d条新消息, 滑动浏览", arr.length()), Toast.LENGTH_SHORT).show()
                    }else{
                        val msg = Message()
                        msg.what = 1
                        msg.obj = "Server overloads"
                        handler.sendMessage(msg)
                        Toast.makeText(this, "超载，请重启软件重试", Toast.LENGTH_SHORT).show()
                        stopEmergency = -2
                    }
                }
                1 -> {
                    tvState.text = it.obj.toString()
                }
                2 -> {
                    msg_list_container.removeAllViews()
                }
            }
            return@Handler true;
        }

        // 根据消息框输入框是否为空来 enable/disable 发送按钮
        class JTextWatcher: TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if(s.toString().isEmpty()){
                    btnSendMsg.isEnabled = false
                }else if(!btnSendMsg.isEnabled){
                    btnSendMsg.isEnabled = true
                }
            }

        }
        etMsg.addTextChangedListener(JTextWatcher())

//        etMsg.setText("213")
        // 点击空白区域使输入框失去焦点，并收起键盘
        _focus.setOnTouchListener { v, event ->
            var count = 0;
            when(event.action){
                MotionEvent.ACTION_DOWN -> {
                    Log.e(TAG, "onCreate: press down")
                    isTouching = true

                    val timer1 = Timer()
                    val countTsk = object: TimerTask() {
                        override fun run() {
                            if(!isTouching){
                                this.cancel()
                                timer1.purge()
                            }
                            count++

                            if(count >= 3){
                                val msg = Message()
                                msg.what = 2
                                handler.sendMessage(msg)
                            }
                        }
                    }
                    timer1.schedule(countTsk, 500, 500)
                }
                MotionEvent.ACTION_UP -> {
                    v.performClick()
                    v.requestFocus()
                    val imm: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(etMsg.windowToken, 0)
                    isTouching = false
                }
            }
            return@setOnTouchListener false
        }

        // 如果消息框不为空，则发送消息； 由于输入框监听器的存在，此判断可去除
        btnSendMsg.setOnClickListener{
            val msg = etMsg.text.toString()
            if(msg.isEmpty() || stopEmergency != 0){
                return@setOnClickListener
            }
            addMsg(it.context, msg)
            etMsg.setText("")
        }
        val ad_listener = AboutDialog.OnClickListener{
            if(it == 1){
                synMsg()
                TipDialog(this).show()
            }
        }
        val ad = AboutDialog(this, ad_listener)
        ad.setCanceledOnTouchOutside(false)
        ad.show()
    }


    fun synMsg(){
        val timer = Timer()
        var timeSyn = 6
        val tsk = object: TimerTask(){
            override fun run() {
                if(stopEmergency < 0){
                    this.cancel()
                    timer.cancel()
                    timer.purge()
                    return
                }
                if(timeSyn-- > 0){
                    val msg = Message()
                    msg.what = 1
                    msg.obj = String.format("%d秒后同步消息", timeSyn)
                    handler.sendMessage(msg)
                    return
                }
                timeSyn = 6
                if(msgLast.length() > 0){
                    SCommThread(0x100, handler, msgLast["date"].toString(), null).start()
                }
                else{
                    SCommThread(0x100, handler, null, null).start()
                }
            }
        }
        timer.schedule(tsk, 0, 1000)
    }
    // 增加消息显示
    fun addMsg(context: Context, msg: String, time: String = ""){
        val timeDisplay: String;
        if(time.isEmpty()) {
            val date = Date()
            val dateFormat = SimpleDateFormat("MM/dd HH:mm:ss", Locale.CHINA)
            timeDisplay = dateFormat.format(date)
            if(stopEmergency == 0) {
                SCommThread(0x101, handler, timeDisplay, msg).start()
            }else if(stopEmergency == -1){
                Toast.makeText(context, "有新版本可下载", Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(context, "服务器超载，请稍后重试", Toast.LENGTH_SHORT).show()
            }
            return
        }else{
            timeDisplay = time
        }
        val title = String.format("[#%d] %s", msgCount, timeDisplay)

        val msgContainer = LinearLayout(context)
        msgContainer.orientation = LinearLayout.VERTICAL
        msgContainer.background = ContextCompat.getDrawable(context, R.drawable.selector_fd_msg)
        val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        lp.setMargins(0, 10, 0, 0)
        msgContainer.layoutParams = lp
        msgContainer.setPadding(5, 0, 5, 0)

        msgContainer.setOnClickListener{
            Toast.makeText(context, "长按2s复制本消息", Toast.LENGTH_SHORT).show()
        }

        msgContainer.setOnLongClickListener {
            val cbm: ClipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            val data = ClipData.newPlainText("msgDetail", msg)
            cbm.setPrimaryClip(data)
            if(cbm.hasPrimaryClip()){
                Toast.makeText(context, "消息已复制", Toast.LENGTH_SHORT).show()
            }
            it.isLongClickable = false
            return@setOnLongClickListener true
        }

        val tvTitle = TextView(msgContainer.context)
        tvTitle.text = title
        tvTitle.textSize = 20f
        
        val tvContent = TextView(msgContainer.context)
        tvContent.text = msg

        msgContainer.addView(tvTitle)
        msgContainer.addView(tvContent)

        msg_list_container.addView(msgContainer)
//        findViewById<ScrollView>(R.id.sv_f).fullScroll(ScrollView.FOCUS_DOWN)
    }
}